var db = require('../models');
var async = require('async');

//根据用户id查找用户
exports.findUserById = function(_userId,callback){
	db.User.findOne({
		_id:_userId,
	},callback);
};
//根据邮箱查找用户，没有则创建
exports.findByEmailOrCreate = function(email,callback){
	db.User.findOne({
		email:email,
	},function(err,user){
		if(user){
			callback(null,user);
		}else{
			var newUser = new db.User({
				name:email.split('@')[0],
				email:email,
			});
			newUser.save(callback);
		}
	});
};
exports.online = function(_userid,callback){
	db.User.findOneAndUpdate({
		_id:_userid,
		online:false,
	},{
		$set:{online:true}
	},callback);
};
exports.offline = function(_userid,callback){
	db.User.findOneAndUpdate({
		_id:_userid,
	},{
		$set:{online:false}
	},callback);
};
exports.getOnlineUser = function(callback){
	db.User.find({online:true},callback);
}
//
exports.joinRoom = function(params,callback){
	db.User.findOneAndUpdate({
		_id:params.userId
	},{
		$set:{
			online:false,
			_roomId:params.roomId
		}
	},function(err,user){
		console.log(user);
		callback(err,user);
	});
}
exports.leaveRoom = function (userid, callback) {
  db.User.findOneAndUpdate({
    _id: userid
  }, {
    $set: {
      online: true,
      _roomId: null
    }
  }, callback)
}